<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form" @submit.prevent>
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请输入要搜索的职位"
          v-model="keyword"
          @keyup.enter="search"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!keyword" @click="search">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" icon="Plus" @click="addRole">添加职位</el-button>
    <el-table border style="margin: 10px 0" :data="allRole">
      <el-table-column
        type="index"
        align="center"
        label="序号"
        width="80px"
      ></el-table-column>
      <el-table-column align="center" label="ID" prop="id"></el-table-column>
      <el-table-column
        align="center"
        label="职位名称"
        show-overflow-tooltip
        prop="roleName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column align="center" label="操作" width="280px">
        <template #default="{ row }">
          <el-button
            type="success"
            size="small"
            icon="User"
            @click="setPermisstion(row)"
          >
            分配权限
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-button type="danger" size="small" icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="sizeChange"
      @current-change="getHasRole"
    />
  </el-card>
  <!-- 添加职位与更新已有职位的结构：对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="RoleParams.id ? '更新职位' : '添加职位'"
  >
    <el-form @submit.prevent :model="RoleParams" :rules="rules">
      <el-form-item label="职位名称" prop="roleName" ref="form">
        <el-input
          placeholder="请输入职位名称"
          v-model="RoleParams.roleName"
          @keyup.enter="save"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <!-- 树形控件-->
      <el-tree
        style="max-width: 600px"
        :data="menuArr"
        ref="tree"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectArr"
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div>
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermisstion,
} from '@/api/acl/role'
import type {
  RoleResponseData,
  Records,
  RoleData,
  MenuResponseData,
  MenuList,
} from '@/api/acl/role/type'
import useLayOutSettingStore from '@/store/modules/setting'

// 当前页码
const pageNo = ref(1)
// 每页的数据
const pageSize = ref(10)
// 搜索关键字
const keyword = ref('')
// 存储全部已有的职位
const allRole = ref<Records>()
// 职位总个数
const total = ref(0)
// 控制对话框显示与隐藏
const dialogVisible = ref(false)
// 收集新增岗位的数据
const RoleParams = ref<RoleData>({
  roleName: '',
})
// 获取form组件实例
const form = ref()
// 获取tree组件实例
const tree = ref()
// 控制抽屉显示与隐藏
const drawer = ref(false)
// 存储用户权限的数据
const menuArr = ref<MenuList>([])
// 准备一个数组:数组用于存储勾选节点的ID
const selectArr = ref()
// 获取setting仓库
const settingStore = useLayOutSettingStore()

// 封装页面渲染函数
const getHasRole = async (pager = 1) => {
  // 修改当前页码
  pageNo.value = pager
  const res: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (res.code === 200) {
    allRole.value = res.data.records
    total.value = res.data.total
  }
}
getHasRole()

// 下拉菜单的回调
const sizeChange = () => {
  getHasRole()
}

// 点击搜索按钮的回调
const search = () => {
  // 判断keyword是否为空
  if (!keyword.value) return
  // 携带关键字发送请求
  getHasRole()
  // 清空数据
  keyword.value = ''
}

// 点击重置按钮的回调
const reset = () => {
  // 刷新页面
  settingStore.refsh()
}

// 添加职位按钮的回调
const addRole = () => {
  // 对话框显示
  dialogVisible.value = true
  // 清空数据
  Object.assign(RoleParams.value, {
    id: 0,
    roleName: '',
  })
  // 清空上一次表单校验的错误信息
  nextTick(() => {
    form.value.clearValidate()
  })
}

// 更新已有的职位按钮的回调
const updateRole = (row: RoleData) => {
  // 对话框显示
  dialogVisible.value = true
  // 清空数据
  Object.assign(RoleParams.value, row)
  // 清空上一次表单校验的错误信息
  nextTick(() => {
    form.value.clearValidate()
  })
}

// 点击确定按钮的回调
const save = async () => {
  // 表单校验
  await form.value.validate()
  // 添加或更新职位的请求
  const res: any = await reqAddOrUpdateRole(RoleParams.value)
  if (res.code === 200) {
    // 提示信息
    ElMessage.success(RoleParams.value.id ? '更新成功' : '添加成功')
    // 关闭对话框
    dialogVisible.value = false
    // 重新获取全部职位列表
    getHasRole(RoleParams.value.id ? pageNo.value : 1)
  }
}

// 分配权限按钮的回调
const setPermisstion = async (row: RoleData) => {
  // 抽屉显示
  drawer.value = true
  // 收集数据
  Object.assign(RoleParams.value, row)
  // 根据职位获取权限的数据
  const res: MenuResponseData = await reqAllMenuList(
    RoleParams.value.id as number,
  )
  if (res.code === 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  } else {
    ElMessage.error('获取权限失败')
  }
}

// 新增递归函数收集四级子节点勾选数据
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}

const defaultProps = {
  children: 'children',
  label: 'name',
}

// 抽屉确定按钮的回调
const confirmClick = async () => {
  // 职位的ID
  const roleId = RoleParams.value.id as number
  // 选中节点的ID
  const arr = tree.value.getCheckedKeys()
  // 半选的ID
  const halfArr = tree.value.getHalfCheckedKeys()
  // 数据合并
  const permissionId = [...arr, ...halfArr]
  // 下发权限的请求
  const res: any = await reqSetPermisstion(roleId, permissionId)
  if (res.code === 200) {
    ElMessage.success('权限分配成功')
    // 关闭抽屉
    drawer.value = false
    // 页面刷新
    window.location.reload()
  } else {
    ElMessage.error('权限分配失败')
  }
}

// 新增职业的表单校验规则
const rules = {
  roleName: [
    {
      required: true,
      trigger: 'blur',
      validator: (rule: any, value: any, callBack: any) => {
        if (value.trim().length >= 2) {
          callBack()
        } else {
          callBack(new Error('职位名称至少2个字符'))
        }
      },
    },
  ],
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
